import random
import string
from django.contrib.auth.models import User, Group
from rest_framework.viewsets import ModelViewSet, ViewSet
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND
from school.models import Classes
from user.serializers import CreateUserSerializer
from .serializers import ClassesSerializer
from rest_framework.permissions import IsAuthenticated
from utils.customPermissions import TeacherPermission
from celery_tasks.email.tasks import send_mail_task


class ClassesViewSet(ModelViewSet):
    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer
    # permission_classes = [IsAuthenticated] #使用内置登录权限
    permission_classes = [TeacherPermission]


class ClassesMemberViewSet(ViewSet):
    pass
    serializer_class = CreateUserSerializer
    # permission_classes = [TeacherPermission]

    def add_member(self, request, pk):

        '''
        1、获取指定的班级
        2、判断是否已经属于该班级，属于  返回‘该成员已加入了该班组’，代码终止
        3、如不属于，判断成员是否注册，已注册，添加班级，代码终止
        4、未注册，注册用户，生成初始密码
        5、新账户放到学生组并添加到班级
        6、通过邮件将账户初始密码发送给学生邮箱
        :param request:
        :param pk:
        :return:
        '''
        try:
            classes = Classes.objects.get(id=pk)
        except Classes.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        username = request.data['username']
        member = classes.member.filter(username=username)
        if member:
            return Response({'msg': '该成员已加入了该班级'})

        user = User.objects.filter(username=username)
        if user:
            classes.member.add(user[0])
            return Response(CreateUserSerializer(user[0]).data)

        user_serializer = CreateUserSerializer(data=request.data)
        user_serializer.is_valid(raise_exception=True)

        first_name = request.data['first_name']
        email = request.data['email']

        user =User(username=username,email=email,first_name=first_name)
        source = string.ascii_letters + string.digits

        password = ''.join(random.sample(source, 6))
        user.set_password(password)
        user.save()
        group = Group.objects.get(id=2)
        group.user_set.add(user)   # 反向
        classes.member.add(user)   # 正向
        # 通过邮件将账号初始密码发送给学生邮箱
        send_mail_task(email, username, password, classes.name)


        return Response(user_serializer.data)